package com.gviiii.baiduai.config;

import com.google.common.base.Strings;
import com.gviiii.baiduai.config.impl.ClasspathStrategy;
import com.gviiii.baiduai.config.impl.FileSystemStrategy;

import java.util.HashMap;
import java.util.Map;

public abstract class AbstractConfigRegistry<K, V> implements ConfigRegistry<K, V> {

    protected static final String AI_ITEM_CONFIG_FILE = "aiItem.properties";

    protected static final String AI_IMG_CONFIG_FILE = "aiImg.properties";

    protected static final String AI_TOKEN_CONFIG_FILE = "token.properties";

    protected Map<String, ServiceConfig> serviceConfigMap = new HashMap<>();

    protected Map<String, ServiceConfig> sdkConfigMap = new HashMap<>();

    protected Map<String, String> tokenConfigMap = new HashMap<>();

    protected AbstractConfigRegistry() {

    }

    protected void initConfigMap(ConfigType type, String localtion) {
        boolean b = Strings.isNullOrEmpty(localtion);
        if (!b) {
            switch (type){
                case TOKEN:registryTokenConfig(localtion);break;
                case IMG:registryServiceConfig(localtion);break;
                case ITEM:registryServiceConfig(localtion);break;
                case SDK:registrySdkConfig(localtion);break;
            }
        }
    }

    private void registryTokenConfig(String localtion) {
        this.tokenConfigMap = ConfigHandler.getTokenConfigMap(executeStrategy(localtion));
    }

    private void registryServiceConfig(String localtion) {
        this.serviceConfigMap = ConfigHandler.getAiConfigMap(executeStrategy(localtion));
    }

    private void registrySdkConfig(String localtion) {
        this.sdkConfigMap = ConfigHandler.getSdkConfigMap(executeStrategy(localtion));
    }

    private Map<String, String> executeStrategy(String srcFile) {
        ConfigStrategy configStrategy = new FileSystemStrategy();
        Map<String, String> map = configStrategy.doOperation(srcFile);
        if (!map.isEmpty()) {
            return map;
        } else {
            configStrategy = new ClasspathStrategy();
            return configStrategy.doOperation(srcFile);
        }
    }
}
